// src/mqtt.js
import mqtt from 'mqtt/dist/mqtt.js' //引入mqtt依赖

let client = null;

export function connectMqtt(options) {
	if (!client) {
		// #ifdef H5              
		client = mqtt.connect('ws://47.117.131.69:5275/mqtt', options);
		// #endif
		// #ifdef MP-WEIXIN||APP-PLUS
		client = mqtt.connect('wx://47.117.131.69:5275/mqtt', options);
		// #endif


		client.on('connect', () => {
			console.log('Connected to MQTT server');
		});

		client.on('error', (err) => {
			console.error('MQTT connection error:', err);
		});

	}
	return client;
}
export function EmitMsg(messageHandler) {
	if (client && messageHandler) {
		client.on('message', (topic, message) => {
			// #ifdef H5    
			const decoder = new TextDecoder('utf-8');
			message = decoder.decode(message);
			// #endif
			messageHandler(topic, message);
		});
	}
}

export function publishMessage(topic, message) {
	if (client) {
		client.publish(topic, message, {}, (err) => {
			if (err) {
				console.error('Message publish error:', err);
			} else {
				console.log('Message published');
			}
		});
	} else {
		console.error('MQTT client is not connected');
	}
}

export function subscribeTopic(topic) {
	if (client) {
		client.subscribe(topic, (err) => {
			if (err) {
				console.error('Subscribe error:', err);
			} else {
				console.log(`Subscribed to topic: ${topic}`);
			}
		});
	} else {
		console.error('MQTT client is not connected');
	}
}

export function disconnectMqtt() {
	if (client) {
		client.end();
		client = null;
	}
}